package team.tunan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import team.tunan.dto.ClientPageDto;
import team.tunan.entity.Client;
import team.tunan.exception.BusinessException;
import team.tunan.mapper.ClientMapper;
import team.tunan.service.IClientService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import static team.tunan.common.HttpCodeEnum.OPERATION_ERROR;
import static team.tunan.utils.BaseRegexPatterns.EMAIL_REGEX;
import static team.tunan.utils.BaseRegexPatterns.PHONE_REGEX;

/**
 * <p>
 * 销售方表 服务实现类
 * </p>
 *
 * @author sqx
 * @since 2023-12-24
 */
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements IClientService {
    @Autowired
    private ClientMapper clientMapper;
    @Override
    public int insertClient(Client client) {
        //新增数据,校验数据是否合规
        //checkClient(client);
        return clientMapper.insert(client);
    }

    @Override
    public int updateClient(Client client) {
        //checkClient(client);
        return clientMapper.updateById(client);
    }

    @Override
    public int deleteCient(String id) {
        return clientMapper.deleteById(id);
    }


    @Override
    public Page<Client> selectPage(ClientPageDto clientPageDto) {
        Page<Client> clientPage = new Page<>(clientPageDto.getCurrentPage(),clientPageDto.getPageSize());
        LambdaQueryWrapper<Client> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(clientPageDto.getAddress())&&!"null".equals(clientPageDto.getAddress())){
            lambdaQueryWrapper.like(Client::getAddress,clientPageDto.getAddress());
        }
        if(StringUtils.isNotBlank(clientPageDto.getName())&&!"null".equals(clientPageDto.getName())){
            lambdaQueryWrapper.like(Client::getName,clientPageDto.getName());
        }
        Page<Client> page = clientMapper.selectPage(clientPage, lambdaQueryWrapper);
        return page;
    }

    @Override
    public Client selectByClientId(Integer id) {
        return clientMapper.selectById(id);
    }


    /**
     * 校验客户的字段是否合法
     * @param client
     */
    private void checkClient(Client client) {
        if(client.getEmail().matches(EMAIL_REGEX)) {
            throw new BusinessException(OPERATION_ERROR.getCode(), "邮箱格式错误，请填写正确的邮箱");
        }
        if(client.getPhone().matches(PHONE_REGEX)) {
            throw new BusinessException(OPERATION_ERROR.getCode(), "手机号格式错误，请填写正确的手机号");
        }
    }
}
